#include "ThreadPool.h"
#include <iostream>

using namespace std;

// 静态实例初始化
ThreadPool& ThreadPool::getInstance() {
    static ThreadPool instance(4); // 假设线程池大小为4
    return instance;
}

// 构造函数
ThreadPool::ThreadPool(size_t numThreads) : stop(false) {
    for (size_t i = 0; i < numThreads; ++i) {
        workers.emplace_back([this] { workerThread(); });
    }
}

// 析构函数
ThreadPool::~ThreadPool() {
    {
        unique_lock<mutex> lock(queueMutex);
        stop = true;
    }
    condition.notify_all();
    for (thread& worker : workers) {
        worker.join();
    }
    cout << "线程池已销毁。" << endl;
}

// 添加任务
void ThreadPool::enqueueTask(function<void()> task) {
    {
        unique_lock<mutex> lock(queueMutex);
        tasks.push(task);
    }
    condition.notify_one();
}

// 工作线程
void ThreadPool::workerThread() {
    while (true) {
        function<void()> task;
        {
            unique_lock<mutex> lock(queueMutex);
            condition.wait(lock, [this] { return stop || !tasks.empty(); });
            if (stop && tasks.empty()) {
                return;
            }
            task = tasks.front();
            tasks.pop();
        }
        task();
    }
}
